﻿/*
   Copyright 2012 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using AopAlliance.Intercept;
using Flower.Logging;

namespace Flower.Processing.Advices
{
    public class StatsCollector : IMethodInterceptor
    {
        private class StatEntry
        {
            public string ActivityName;
            public long NumberOfExecutions;
            public TimeSpan TotalTime;

            public TimeSpan AvgTime { get { return TimeSpan.FromMilliseconds(TotalTime.TotalMilliseconds / NumberOfExecutions); } }
        }
        
        private static readonly Log Log = LogManager.CreateLog(typeof(StatsCollector).Name);

        private readonly ConcurrentDictionary<string, StatEntry> _stats =
            new ConcurrentDictionary<string, StatEntry>();
        private readonly Timer _printTimer;

        public StatsCollector(TimeSpan printInterval)
        {
            _printTimer = new Timer
            (
                _ => PrintStats(),
                null,
                printInterval,
                printInterval
            );
        }

        private void PrintStats()
        {
            var stat =
                _stats
                    .Values
                    .OrderByDescending(s => s.AvgTime)
                    .ToList();

            if (stat.Count > 0)
            {
                Log.Info("Statistics collected:");

                foreach (StatEntry statEntry in stat)
                {
                    var s = statEntry;
                    Log.Info
                    (
                        () =>
                            string.Format
                            (
                                "{0}: total time {1}, avg. time {2}, number of execs {3}.",
                                s.ActivityName,
                                s.TotalTime,
                                s.AvgTime,
                                s.NumberOfExecutions
                            )
                    );
                }
            }
        }

        public object Invoke(IMethodInvocation invocation)
        {
            if (invocation.Method.Name != "Do")
            {
                return invocation.Proceed();
            }

            var activity = invocation.Target as Activity;
            if (activity == null)
            {
                return invocation.Proceed();
            }

            var processor = invocation.Arguments[0] as Processor;
            if (processor == null)
            {
                return invocation.Proceed();
            }

            var started = DateTime.Now;
            try
            {
                return invocation.Proceed();
            }
            finally
            {
                var ended = DateTime.Now;

                string actName = string.Concat(activity.Name, "@", processor.State.GetType().FullName);

                _stats.AddOrUpdate
                (
                    actName,
                    actKey => new StatEntry
                    {
                        ActivityName = actName,
                        NumberOfExecutions = 1,
                        TotalTime = ended - started
                    },
                    (methodName, stat) =>
                    {
                        stat.NumberOfExecutions++;
                        stat.TotalTime += ended - started;
                        return stat;
                    }
                );
            }
        }
    }
}
